#include "shortsound2txt.h"
#include <QFile>
#include <QDataStream>

#define URL_MODE 1;
// 极速版
#define URL_QUICK "http://vop.baidu.com/pro_api"
// 标准版
#define URL_STAND "http://vop.baidu.com/server_api"

ShortSound2Txt::ShortSound2Txt(QObject *parent) : SoundBase(parent)
{

}

QString ShortSound2Txt::getRepostUrl(QString apiId, QString accessToken)
{
    // POST http://vop.baidu.com/server_api
    QString url = QString("http://vop.baidu.com/server_api?lan=zh&cuid=%1&token=%2")
            .arg(apiId).arg(accessToken);
    return url;
}

QString ShortSound2Txt::getResult(QString para_API_record_path)
{
    QString ret = "";
    QFile file(para_API_record_path);
    if( !(file.open(QIODevice::ReadOnly)))
    {
        qWarning("打开语音文件失败！");
        return ret;
    }
#if 1
    // 方式一：raw
    /*读入文件流*/
    QDataStream in(&file);
    char *m_buf =new char[file.size()];
    in.readRawData(m_buf,file.size());
    file.close();

    //QString  getTextUrl = "http://vop.baidu.com/server_api?lan=" + para_API_language + "&cuid=" + para_API_id + "&token=" + para_API_access_token;
    QString getTextUrl = getRepostUrl(API_id,API_access_token);

    /*发送http请求给百度语音,从而得到语音文本*/
    QUrl url;
    url.setUrl(getTextUrl);
    QNetworkRequest request(url);
    // Head
    request.setHeader(QNetworkRequest::ContentTypeHeader, "audio/pcm;rate=16000");
    QByteArray arr = QByteArray(m_buf, file.size());
    QByteArray result = post(request,arr);
#else
    // 方式二：json
    QByteArray fileData = file.readAll();
    file.close();

    //QString getTextUrl = URL_STAND;
    QString getTextUrl = URL_QUICK;

    /*发送http请求给百度语音,从而得到语音文本*/
    QUrl url;
    url.setUrl(getTextUrl);
    QNetworkRequest request(url);
    // Head
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    // Body
    QVariantMap map;
    map["format"]  = QString("m4a");
    map["pid"]     = 80001;
    map["rate"]    = 16000;
    map["dev_pid"] = 1537;
    map["channel"] = 1;
    map["token"]   = API_access_token,
    map["cuid"]    = API_id;
    map["len"]     = fileData.length();
    map["speech"]  = fileData.data();
    QByteArray body = QJsonDocument::fromVariant(map).toJson(QJsonDocument::Indented);
    QByteArray result = post(request,body);
#endif
    qDebug() << result;
    ret = parasePostResult(result);
    return ret;
}

QString ShortSound2Txt::parasePostResult(QByteArray jsonString)
{
    QString ret = "";
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(jsonString, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
       qDebug() << "BaiDu json error!";
       return ret;
    }
    QJsonObject rootObj = jsonDoc.object();
    //获取键值，用于查看返回到所有键（可以注释掉）
    QStringList keys = rootObj.keys();
    for(int i = 0; i < keys.size(); i++)
    {
       qDebug() << "key" << keys << " is:" << keys.at(i);
    }
    //获取转化回来的文本内容
    if(rootObj.contains("err_no"))
    {
       if(0==rootObj.take("err_no").toVariant().toString())
       {
             qWarning("语音识别错误!");
       }
       else
       {
           QJsonArray subArray = rootObj.value("result").toArray();
           for(int i = 0; i< subArray.size(); i++)
           {
               QString str = subArray.at(i).toString();
               qDebug()<<str;
               ret += str;
           }
       }
    }
    return ret;
}

